
import 'package:extended_image/extended_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/page/user/appointmentInfo.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/publicUtil.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:azlistview/azlistview.dart';
import 'package:gd_assistant/model/doctorModel.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/model/extensionModel.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/page/public/publicView.dart';

class SortCondition {
  String name;
  bool isSelected;
  String value;
  int index;

  SortCondition({this.name, this.isSelected, this.value, this.index});
}

class extensionPage extends StatefulWidget {
  @override
  _extensionPageState createState() => _extensionPageState();
}

class _extensionPageState extends State<extensionPage> {
  bool isDark = false;
  GZXDropdownMenuController _dropdownMenuController = GZXDropdownMenuController();
  GlobalKey _stackKey = GlobalKey();
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  List<String> _dropDownHeaderItemStrings = ['12-18(今天)', '未就诊', '全部医生'];
  List<SortCondition> _brandSortConditions = [];
  SortCondition _selectBrandSortCondition;

  List<SortCondition> _clinicStatusConditions = [
    SortCondition(name: '全部状态', isSelected: false),
    SortCondition(name: '未就诊', isSelected: true),
    SortCondition(name: '已就诊', isSelected: false),
    SortCondition(name: '已取消', isSelected: false)
  ];
  SortCondition _selectClinicStatusCondition;

  List<DoctorModel> _doctorList = List();
  List<DoctorModel> _selectdoctorList = List();
  int _suspensionHeight = 40;
  int _itemHeight = 50;
  String _suspensionTag = "";
  String _resetTitle = "重置(默认全部)";
  int page = 0;
  List<Extension> _extensionList;

  RefreshController _refreshController =
      RefreshController(initialRefresh: true);
  
  //解决滑动问题
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    super.initState();
    _selectClinicStatusCondition = _clinicStatusConditions[1];
    page = 0;
    setupDateModel();
    publicUtil.getServiceDoctor(_doctorList);
  }

  void setupDateModel() {
    //前取30天 后取30天 name 里面存时间戳 一天的时间戳86400000
    var time = new DateTime.now().toString();
    time = time.substring(0,10);
    int timespace = DateTime.parse(time).millisecondsSinceEpoch;
    
    for (var i = -30; i < 30; i++) {
      var name = DateTime.fromMillisecondsSinceEpoch(timespace + i * 86400000);
      var week;
      switch (name.weekday) {
        case 7:
          week = "周日";
          break;
        case 1:
          week = "周一";
          break;
        case 2:
          week = "周二";
          break;
        case 3:
          week = "周三";
          break;
        case 4:
          week = "周四";
          break;
        case 5:
          week = "周五";
          break;
        case 6:
          week = "周六";
          break;          
        default:
      }
      var sort = SortCondition(name: name.toString().substring(5,10)+" (${i == 0 ? "今天" : week})", isSelected: i == 0 ? true : false, value: (timespace + i * 86400000).toString(), index: i+30);
      _brandSortConditions.add(sort);
      if (i == 0) {
        _dropDownHeaderItemStrings[0] = sort.name;
        _selectBrandSortCondition = sort;
      }
    }

  }

  void _onRefresh () async {
    page = 0;
    List<String> doctorids = _selectdoctorList.map((v)=>v.id).toList();
    List<Extension> result = await apiHandler.getMemberShipList(_selectBrandSortCondition.value,_selectClinicStatusCondition.name,doctorids,page);
    if(mounted)
    setState(() {
      _extensionList = result;
    });
     _refreshController.refreshCompleted();
  }

  void _onLoading () async {
    page ++;
    List<String> doctorids = _selectdoctorList.map((v)=>v.id).toList();
    List<Extension> result = await apiHandler.getMemberShipList(_selectBrandSortCondition.value,_selectClinicStatusCondition.name,doctorids,page);
    if(mounted)
    _extensionList.addAll(result);
    setState(() {
      _extensionList = _extensionList;
    });
     _refreshController.loadComplete();
  }

  void _onSusTagChanged(String tag) {
    setState(() {
      _suspensionTag = tag;
    });
  }

  Widget _buildSusWidget(String susTag) {
    return Container(
      height: _suspensionHeight.toDouble(),
      padding: const EdgeInsets.only(left: 15.0),
      color: isDark ? Colours.dark_bg_color : Color(0xfff3f4f5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xff999999),
        ),
      ),
    );
  }


  Widget _buildListItem(DoctorModel model) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        SizedBox(
          height: _itemHeight.toDouble(),
          child: GestureDetector(
            onTap: (){
              print("OnItemClick: $model");
              int count = 0;
              _doctorList.forEach((v){
                if (v.id == model.id) {
                  v.isSelected = !model.isSelected;
                }
                if (v.isSelected) {
                  count ++;
                }
              });

              setState(() {
                _resetTitle = count > 0 ? "重置(已选${count}位)" : "重置(默认全部)";
              });
            },
            child: Row(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(left: 20,right: 10),
                  child:  ClipRRect(
                    borderRadius: BorderRadius.circular(36),
                    child: ExtendedImage.network(
                      GlobalConfig.qiNiuUri+model.avatar,
                      height: 36,
                      width: 36,
                      fit: BoxFit.fitWidth,
                    ),
                  ),
                ),
                Container(
                  width: MediaQuery.of(context).size.width/3-66,
                  child: Text(model.name, style: TextStyle(fontSize: 16),maxLines: 1,overflow: TextOverflow.ellipsis),
                ),
                Container(
                  width: MediaQuery.of(context).size.width/3+40,
                  child: Text(model.hospital, style: TextStyle(fontSize: 14),maxLines: 1,overflow: TextOverflow.ellipsis),
                ),
                Container(
                  color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                  width: MediaQuery.of(context).size.width/3-40,
                  child: Center(
                    child: model.isSelected ? Icon(Icons.check_box, size: 16, color: Colors.blue,): Icon(Icons.check_box_outline_blank, size: 16)
                  ),
                ),
              ],
            ),
          )
        )
      ],
    );
  }



  Widget header(context) {
    return GZXDropDownHeader(
      items: [
        GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
        GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
        GZXDropDownHeaderItem(_dropDownHeaderItemStrings[2]),
      ],
      stackKey: _stackKey,
      controller: _dropdownMenuController,
      onItemTap: (index) {
        //如果 index = 0 自动划到选中那里
        if (index == 0 && _dropdownMenuController.isShow) {
           //计算选中的 index
          _scrollController.animateTo((_selectBrandSortCondition.index).toDouble()*45.3, duration: new Duration(milliseconds: 10), curve: Curves.ease);
        }
        //如果是 index = 1 主要是收了动画
        if (index == 1 && _dropdownMenuController.isShow) {
          _scrollController.animateTo(0, duration: new Duration(milliseconds: 10), curve: Curves.ease);
        }
        //如果是 index = 2 判断是收起状态
        if (index == 2 && _dropdownMenuController.isShow) {
          //如果没拉到 再拉一次
          if (_doctorList.length == 0) {
            publicUtil.getServiceDoctor(_doctorList);
          }
          //同步维护的数组 和 跟数组
          int count = 0;
          for (var i = 0; i < _doctorList.length; i++) {
            DoctorModel ct = _doctorList[i];
            ct.isSelected = false;
            for (var j = 0; j < _selectdoctorList.length; j++) {
              DoctorModel sel = _selectdoctorList[j];
              if (ct.id == sel.id) {
                ct.isSelected = true;
                count ++;
              }
            }
          }

          setState(() {
            _resetTitle = count > 0 ? "重置(已选${count}位)" : "重置(默认全部)";
          });
        }
      },
      height: 45,
      color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
      borderWidth: 1,
      borderColor: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
      dividerHeight: 20,
      dividerColor: isDark ? Colours.dark_text_gray : Colours.text_gray,
      style: TextStyle(color: Color(0xFF666666), fontSize: 14),
      dropDownStyle: TextStyle(
        fontSize: 14,
        color: Theme.of(context).primaryColor,
      ),
      iconSize: 20,
      iconColor: isDark ? Colours.dark_text_gray : Colours.text_gray,
      iconDropDownColor: Theme.of(context).primaryColor,
    );
  }

  Widget menu(context) {
    return GZXDropDownMenu(
      controller: _dropdownMenuController,
      animationMilliseconds: 100,
      menus: [
        GZXDropdownMenuBuilder(
            dropDownHeight: (45 + 0.3) * 8.0,
            dropDownWidget: _buildDropWidget(_brandSortConditions, (value) {
              _selectBrandSortCondition = value;
              _dropDownHeaderItemStrings[0] = _selectBrandSortCondition.name;
              _dropdownMenuController.hide();
              setState(() {});
              _onRefresh();
            },(value){})),
        GZXDropdownMenuBuilder(
            dropDownHeight: (45 + 0.3) * 4.0 - 0.3,
            dropDownWidget: _buildDropWidget(_clinicStatusConditions, (value) {
              _selectClinicStatusCondition = value;
              _dropDownHeaderItemStrings[1] = _selectClinicStatusCondition.name;
              _dropdownMenuController.hide();
              setState(() {});
              _onRefresh();
            },(value){})),
        GZXDropdownMenuBuilder(
            dropDownHeight: MediaQuery.of(context).size.height - (MediaQuery.of(context).padding.top + 56 + 45 + 55 + (MediaQuery.of(context).padding.top == 44.0 ? 28 : 0)),
            dropDownWidget: _buildDropWidget([], (value){}, (value) {
              _dropDownHeaderItemStrings[2] = value.length > 0 ? "已选医生(${value.length})" : "全部医生";
              _dropdownMenuController.hide();
              setState(() {});
              _onRefresh();
            }, isList: false)),
      ],
    );
  }

  _buildDropWidget(List items, void itemOnTap(SortCondition sortCondition), void itemsOnTap(List<DoctorModel> selectDoctors), {bool isList: true}) {
    return Stack(
      children: <Widget>[
        Positioned(
          child: Offstage(
            offstage: !isList,
            child: _buildConditionListWidget(items, itemOnTap),
          ),
        ),
        Positioned(
          child: Offstage(
              offstage: isList,
              child: _buildDoctorListWidget(itemsOnTap),
            ),
        )
      ],
    );
  }

  _buildConditionListWidget(items, void itemOnTap(SortCondition sortCondition)) {
    return ListView.separated(
      controller: _scrollController,
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) => Divider(height: 0.3),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        SortCondition goodsSortCondition = items[index];
        return GestureDetector(
          onTap: () {
            for (var value in items) {
              value.isSelected = false;
            }
            goodsSortCondition.isSelected = true;
            itemOnTap(goodsSortCondition);
          },
          child: Container(
            height: 45,
            color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    goodsSortCondition.name,
                    style: TextStyle(
                      color: goodsSortCondition.isSelected ? Theme.of(context).primaryColor :  isDark ? Colours.dark_text_gray : Colours.text_gray,
                    ),
                  ),
                ),
                goodsSortCondition.isSelected
                    ? Icon(
                        Icons.check,
                        color: Theme.of(context).primaryColor,
                        size: 16,
                      )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  _buildDoctorListWidget(void itemOnTap(List<DoctorModel> selectDoctors)) {
    return Container(
      color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
      child: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: AzListView(
                  data: _doctorList,
                  itemBuilder: (context, model) => _buildListItem(model),
                  suspensionWidget: _buildSusWidget(_suspensionTag),
                  isUseRealIndex: true,
                  itemHeight: _itemHeight,
                  suspensionHeight: _suspensionHeight,
                  onSusTagChanged: _onSusTagChanged,
                ),
          ),
          Container(
            padding: EdgeInsets.fromLTRB(60, 5, 30, 5),
            color: isDark ? Colours.dark_bg_color : Colors.white,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                  Expanded(
                  flex: 1,
                  child: FlatButton(
                    color: isDark ? Colours.dark_bg_gray : Colors.grey[100],
                      shape: StadiumBorder(side: BorderSide.none),
                    textColor: Colors.blue,
                    child: Text(_resetTitle),
                    onPressed: (){
                      _doctorList.forEach((v){
                        v.isSelected = false;
                      });
                      setState(() {
                        _resetTitle = "重置(默认全部)";
                      });
                    },
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 10),
                ),
                Expanded(
                  flex: 1,
                  child: FlatButton(
                    color: Colors.blue,
                      shape: StadiumBorder(side: BorderSide.none),
                    textColor: Colors.white,
                    child: Text("确认"),
                    onPressed: (){
                      _selectdoctorList = [];
                      _doctorList.forEach((v){
                        if (v.isSelected) {
                          _selectdoctorList.add(v);
                        }
                      });
                      itemOnTap(_selectdoctorList);
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _userListItem(BuildContext context, Extension ext) {
    // 全部：-100，未就诊:200，已就诊:400，已取消:300 处理数据
    String status = "未就诊";
    Color bgColor = Colors.blue;
    switch (ext.order.status) {
      case 200:
        status = "未就诊";
        bgColor = Colors.blue;
        break;
      case 300:
        status = "已取消";
        bgColor = Colors.grey[300];
      break;
      case 400:
        status = "已就诊";
        bgColor = Colors.yellow[600];
      break;
      default:
    }
    String medical_num = ext.order.medicalNumber != null ? ext.order.medicalNumber : "无";
    String desc = ext.order.desc != null ? ext.order.desc : "无";
    String tags = "";
    
    ext.order.items.forEach((value){
      tags = tags + value + " ";
    });

    String costType = ext.user.costType.length > 0 ? (","+ext.user.costType) : "";
    
    return GestureDetector(
      onTap: (){
          Navigator.of(context).push(
            CustomRoute(appointmentInfoPage(exten: ext, callBack: (){ _onRefresh(); }),routeName: "/appointmentInfo")
          ); 
      },
      child: Container(
          margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Container(
              child: Row(
                children: <Widget>[
                  Container(
                    color: bgColor,
                    width: 130,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.fromLTRB(20, 12, 20, 2),
                          child: Text(RelativeDateFormat.HMformat(ext.order.workTime),style: TextStyle(fontSize: 25,color: Colors.white,fontWeight: FontWeight.w700)),
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(20, 0, 20, 12),
                          child: Text(RelativeDateFormat.YMDformat(ext.order.workTime),style: TextStyle(fontSize: 15,color: Colors.white)),
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(20, 0, 20, 4),
                          child: Text(status,style: TextStyle(fontSize: 15,color: Colors.white)),
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
                          child: Text(ext.doctor.name + " 医生",style: TextStyle(fontSize: 15,color: Colors.white),maxLines: 1),
                        )
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      color: isDark ? Colours.dark_bg_gray : Colours.bg_gray,
                      child: Stack(
                        children: <Widget>[
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.fromLTRB(20, 14, 20, 13),
                                child: Row(
                                  children: <Widget>[
                                    Text(ext.user.name,style: TextStyle(fontSize: 17,fontWeight: FontWeight.w500)),
                                    Text(" (${ext.user.sex}, ${ext.user.age} ${costType})",style: TextStyle(fontSize: 14,color: Colors.grey)),
                                  ],
                                )
                              ),
                              Padding(
                                padding: EdgeInsets.fromLTRB(20, 0, 20, 4),
                                child: Text("就诊卡号: "+medical_num,style: TextStyle(fontSize: 15,color: Colors.grey[600]),maxLines: 1,overflow: TextOverflow.ellipsis),
                              ),
                              Padding(
                                padding: EdgeInsets.fromLTRB(20, 0, 20, 4),
                                child: Text("预约项目: "+tags,style: TextStyle(fontSize: 15,color: Colors.grey[600]),maxLines: 1,overflow: TextOverflow.ellipsis),
                              ),
                              Padding(
                                padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
                                child: Text("预约详情: "+ desc,style: TextStyle(fontSize: 15,color: Colors.grey[600]),maxLines: 1,overflow: TextOverflow.ellipsis),
                              ),
                            ],
                          ),
                          Positioned(
                            right: 0,
                            top: 14,
                            child: Offstage(
                              offstage: ext.order.weekStr.length == 0,
                              child: Container(
                                padding: EdgeInsets.only(left:8, right:8, top: 3, bottom: 3),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(10), bottomLeft: Radius.circular(10)),
                                    color: Colors.red[200]
                                ),
                                child: Text(ext.order.weekStr,style: TextStyle(color: Colors.white, fontSize: 12)),
                              ),
                            )
                          )
                        ],
                      )
                    ),
                  )
                ],
              ),
            ),
          )
        ) 
    );
  }

  Widget getContentWidget() {
    if (_extensionList != null && _extensionList.length == 0 && _refreshController.isRefresh == false && _refreshController.isLoading == false) {
      return Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children:[
              Image.asset("images/dataBg.png",width: 180),
              Text("暂无预约")
            ]
          ),
      );
    }
    return ListView.separated(
            itemBuilder: (context, item) {
              return _userListItem(context, _extensionList[item]);
            },
            separatorBuilder: (BuildContext context, int index) =>  Container(),
            itemCount: _extensionList != null ? _extensionList.length : 0,
          );
  }

  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        title: new Text('预约管理'),
        elevation: 0
      ),
      body: Stack(
        key: _stackKey,
        children: <Widget>[
          Container(
            child: Column(
              children: <Widget>[
                header(context),
                Expanded(
                    flex: 1,
                    child: SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: _extensionList != null && _extensionList.length > 19,
                      controller: _refreshController,
                      onRefresh: _onRefresh,
                      onLoading: _onLoading,
                      header: ZLRefreshHeader(),
                      footer: ZLRefreshFooter(),
                      child: getContentWidget()
                    )
                )
              ],
            ),
          ),
          menu(context)
        ],
      ),
    );
  }
  @override
  void dispose() {
    super.dispose();
    _dropdownMenuController.dispose();
    _refreshController.dispose();
    _scrollController.dispose();
  }
}


